import { ITodoData } from "../src/typing"
import TodoEvent from './Event/TodoEvent'

((doc) => {
    const oInput: HTMLInputElement = document.querySelector('input')
    const oAddBtn: HTMLElement = document.querySelector('button')
    const oToList: HTMLElement = document.querySelector('.todo-list')

    const todoData: ITodoData[] = [{
        id: 1,
        content: '李白',
        completed: true
    }, {
        id: 2,
        content: '杜甫',
        completed: false
    }, {
        id: 3,
        content: '白居易',
        completed: true
    }]

    const todoEvent = new TodoEvent(todoData, oToList)

    const init = (): void => {
        bindEvent()
    }

    function bindEvent(): void {
        oAddBtn.addEventListener('click', handleBtnClick, false)
        oToList.addEventListener('click', handleListClick, false)
    }
    function handleBtnClick(): void {
        const val: string = oInput.value.trim()
        if (val) {
            todoEvent.addTodo(<ITodoData>{
                id: Math.random(),
                content: val,
                completed: false
            })
            oInput.value = ''

        }
    }
    function handleListClick(e: MouseEvent) {       
        const tar = <HTMLElement>e.target
        const tarName = tar.tagName.toLowerCase()

        if (['input', 'button'].includes(tarName)) {
            const id: number = Number(tar.dataset.id)
            switch (tarName) {
                case 'input':
                    todoEvent.toggleComplete(id, tar)
                    break
                case 'button':
                    todoEvent.removeTodo(id, tar)
                    break
                default:
                    break
            }
        }
    }
    init()

})(document)
